package thread.chapter03;

import java.util.concurrent.atomic.AtomicLong;

/**
 * @author xinya
 * @version 1.0
 * @project javacore
 * @description 原子操作
 * @date 2023/12/18 15:51:37
 */
public class Atomic {

    private static AtomicLong atomicLong = new AtomicLong(0);
//    创建数据
    private static Integer[] arrayOne = new Integer[] {0 , 1 , 2 , 3 , 0 , 5 , 6 , 0 , 56 , 0} ;
    private static Integer[] arrayTwo =new Integer[] {10 , 1 , 2 , 3 , 0 , 5 , 6 , 0 , 56 , 0} ;


    public static void main(String[] args) throws InterruptedException {
        // 线程1统计0的数量
        Thread threadOne = new Thread(new Runnable() {
            @Override
            public void run() {
                int size = arrayOne.length;

                for (var i = 0; i < size; ++ i) {

                    if(arrayOne[i].intValue() == 0) {
                        atomicLong.incrementAndGet();
                    }
                }
            }
        });

        // 线程2统计0的数量
        Thread threadTwo = new Thread(new Runnable() {
            @Override
            public void run() {
                int size = arrayTwo.length;

                for (var i = 0; i < size; ++ i) {

                    if(arrayTwo[i].intValue() == 0) {
                        atomicLong.incrementAndGet();
                    }
                }
            }
        });

        threadOne.start();
        threadTwo.start();

        threadOne.join();
        threadTwo.join();

        System.out.println("count 0:" + atomicLong.get());
    }


}
